<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,模块化," />










<meta name="description" content="前置阅读：简述JavaScript模块化（一） 在前面一文中，我们对前端模块化所经历的三个阶段进行了了解：  CommonJs,由于是同步的，所有主要应用于服务器端，以Node.js为代表。 AMD，异步模块定义，预加载，推荐依赖前置。以require.js为代表。 CMD，通用模块加载，懒加载，推荐依赖就近。以Sea.js为代表。  而在ES6已经大行其道的今天，ES6中所提供的模块化的方法也自">
<meta name="keywords" content="JavaScript,模块化">
<meta property="og:type" content="article">
<meta property="og:title" content="简述JavaScript模块化历程（二）">
<meta property="og:url" content="http://srtian96.gitee.io/blog/2018/05/06/简述JavaScript模块化（二）/index.html">
<meta property="og:site_name" content="Srtian&#39;Blog">
<meta property="og:description" content="前置阅读：简述JavaScript模块化（一） 在前面一文中，我们对前端模块化所经历的三个阶段进行了了解：  CommonJs,由于是同步的，所有主要应用于服务器端，以Node.js为代表。 AMD，异步模块定义，预加载，推荐依赖前置。以require.js为代表。 CMD，通用模块加载，懒加载，推荐依赖就近。以Sea.js为代表。  而在ES6已经大行其道的今天，ES6中所提供的模块化的方法也自">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-05-24T11:26:06.707Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="简述JavaScript模块化历程（二）">
<meta name="twitter:description" content="前置阅读：简述JavaScript模块化（一） 在前面一文中，我们对前端模块化所经历的三个阶段进行了了解：  CommonJs,由于是同步的，所有主要应用于服务器端，以Node.js为代表。 AMD，异步模块定义，预加载，推荐依赖前置。以require.js为代表。 CMD，通用模块加载，懒加载，推荐依赖就近。以Sea.js为代表。  而在ES6已经大行其道的今天，ES6中所提供的模块化的方法也自">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://srtian96.gitee.io/blog/2018/05/06/简述JavaScript模块化（二）/"/>





  <title>简述JavaScript模块化历程（二） | Srtian'Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Srtian'Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">It's better to burn out than to fade away</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://srtian96.gitee.io/blog/blog/2018/05/06/简述JavaScript模块化（二）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Srtian">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Srtian'Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">简述JavaScript模块化历程（二）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-06T12:22:54+08:00">
                2018-05-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,904
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>前置阅读：<a href="https://www.jianshu.com/p/3fbaa3ae70e6/" target="_blank" rel="noopener">简述JavaScript模块化（一）</a></p>
<p>在前面一文中，我们对前端模块化所经历的三个阶段进行了了解：</p>
<ol>
<li>CommonJs,由于是同步的，所有主要应用于服务器端，以Node.js为代表。</li>
<li>AMD，异步模块定义，预加载，推荐依赖前置。以require.js为代表。</li>
<li>CMD，通用模块加载，懒加载，推荐依赖就近。以Sea.js为代表。</li>
</ol>
<p>而在ES6已经大行其道的今天，ES6中所提供的模块化的方法也自然而然成了我们进行JavaScript模块化编程的标准，因此ES6模块的语法虽然在一些较为老的浏览器上不能直出，需要进行转译，但却代表着未来的JavaScript发展趋势。</p>
<h4 id="ES6模块特性"><a href="#ES6模块特性" class="headerlink" title="ES6模块特性"></a>ES6模块特性</h4><p>在ES6中将模块认为是自动运行在严格模式下并且没有办法退出运行的JavaScript代码。在一个模块中定义的变量不会自动被添加到全局共享的作用域之中，这个变量只能作用在这个作用域中。此外模块还必须导出一些外部文件可以访问的元素，以供其他模块或代码使用。</p>
<p>除了这个基本特性，ES6模块还有两大特性也十分重要，需要额外注意：</p>
<ul>
<li>首先是在模块的顶部this值是undefined，这是由于在ES6中的模块的代码是在严格模式下执行的。（如果对this不是很熟悉的可以去看我的这篇文章<a href="https://www.jianshu.com/p/8d6cc7ad9c58/" target="_blank" rel="noopener">：深入浅出this关键字</a>）</li>
<li>其次，模块不支持HTML风格的代码注释，这是早期浏览器所遗留下的JavaScript特性，在ES6的语法里不予支持。</li>
</ul>
<h4 id="基本用法-模块加载"><a href="#基本用法-模块加载" class="headerlink" title="基本用法-模块加载"></a>基本用法-模块加载</h4><p>首先我们来看浏览器是如何加载模块的。其实在ES6规范出来之前，web浏览器就规定了三种方式来引入JavaScript文件：</p>
<ul>
<li>在没有src属性的script元素中直接内嵌JavaScript代码</li>
<li>在 script 元素中通过src属性指定一个地址来加载JavaScript代码文件</li>
<li>通过Web Worker或Service Worker的方法加载并执行JavaScript代码</li>
</ul>
<p>而在浏览器中，默认的行为就是将JavaScript作为脚本来进行加载，而非模块。所以我们要告诉浏览器我们加载的是模块，方法就是在 script 元素中，将type属性指定为”module”。具体看下面的示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 第一种方式</span></span><br><span class="line">&lt;script type=<span class="string">""</span><span class="built_in">module</span>&gt;</span><br><span class="line">    <span class="keyword">import</span> &#123; add &#125; <span class="keyword">from</span> <span class="string">"./example"</span>;</span><br><span class="line">    <span class="keyword">let</span> num = add(<span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/  第二种方式</span></span><br><span class="line"><span class="regexp">&lt;script type="module" src="example.js"&gt;</span></span><br><span class="line"><span class="regexp">/</span><span class="regexp">/ 第三种方式，以脚本的方式加载example.js</span></span><br><span class="line"><span class="regexp">let worker = new Worker("example.js");</span></span><br></pre></td></tr></table></figure>
<p>当HTML解析器遇到script元素的type=”module”的时候，模块文件就开始下载，直到文件被完全解析完成才会去执行模块内的代码。模块文件是按照他们出现在HTML文件中顺序执行的.</p>
<h4 id="基本用法-导出"><a href="#基本用法-导出" class="headerlink" title="基本用法-导出"></a>基本用法-导出</h4><p>在ES6中我们可以使用export关键字将一部分代码暴露给其他模块，以供其他模块或代码使用。先让我们来看看export关键字在MDN的定义吧：</p>
<blockquote>
<p>export语句用于在创建JavaScript模块时，从模块中导出函数、对象或原始值，以便其他程序可以通过 import 语句使用它们。（<br>此特性目前仅在 Safari 和 Chrome 原生实现。它在许多转换器中实现，如Traceur Compiler，Babel或Rollup。）</p>
</blockquote>
<p>通过MDN的定义我们可以知道：export关键字可以将其放在任何函数、对象或原始值前面，从而将它们从模块中导出。示例如下：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   ./example.js</span></span><br><span class="line"><span class="comment">// 导出变量</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="comment">// 导出函数</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">addA</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> value + a;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//导出类</span></span><br><span class="line"><span class="keyword">export</span> <span class="class"><span class="keyword">class</span> <span class="title">add1</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>(value) &#123;</span><br><span class="line">        <span class="keyword">this</span>.value = value + a;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这个函数就是这个模块所私有的，在外部不能访问它</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">say1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'我是不是很帅'</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这又是个函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">say2</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'没错我就是很帅'</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//在后面对函数进行导出,它就不是私有的了</span></span><br><span class="line"><span class="keyword">export</span> say2;</span><br></pre></td></tr></table></figure></p>
<p>需要注意的是：使用export导出的函数和类都需要一个名称，除非使用default关键字，否则就不能用这个方法导出匿名函数或类。所以当我们需要导出匿名的函数或者类时，我们可以这么做：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   ./example.js</span></span><br><span class="line"><span class="comment">//导出匿名函数</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b；</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//或者导出匿名的类</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> </span>&#123;</span><br><span class="line">consturctor(value) &#123;</span><br><span class="line">    <span class="keyword">this</span>.value = value + <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>具体关于default关键字的用法我会在后面做具体介绍，现在只需记住：当我们需要导出匿名的函数或者类时要使用export default语法。</p>
<h4 id="基本语法-导入"><a href="#基本语法-导入" class="headerlink" title="基本语法-导入"></a>基本语法-导入</h4><p>在ES6中，从模块中导入的功能可以通过import关键字。import语句由两部分组成：要导入元素的标识符和元素应当从哪个模块导入。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  ./say.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; say2 &#125; <span class="keyword">from</span> <span class="string">"./example.js"</span>;</span><br><span class="line"><span class="built_in">console</span>.log(say2()); <span class="comment">// '没错我就是很帅'</span></span><br></pre></td></tr></table></figure>
<p>import 后面的大括号中的say2表示从规定模块导入的元素的名称。关键字from后面的字符串则表示要导入的模块的路径，这通常是包含模块的.js文件的相对或绝对路径名，需要注意的是只允许使用单引号和双引号的字符串来包裹路径，浏览器使用的路径格式与传给 script 元素的相同，所以必须把文件的扩展名也加上。</p>
<blockquote>
<p>（注：由于Node.js遵循基于文件系统前缀以区分本地文件个包的惯例，即example是一个包，而./exampple.js是一个本地文件。为了更好的兼容多个浏览器Node.js环境，我们一定要在路径前包含./或../来表示要导入的文件。）</p>
</blockquote>
<p>除此之外，我们还可以导入多个元素或者直接导入整个模块：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入多个元素</span></span><br><span class="line">improt &#123; a, addA, say2 &#125; <span class="keyword">from</span> <span class="string">"./example.js"</span>;</span><br><span class="line"><span class="built_in">console</span>.log(a); <span class="comment">// 1</span></span><br><span class="line">sonsole.log(addA(<span class="number">1</span>); <span class="comment">// 2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 导入整个模块</span></span><br><span class="line"><span class="keyword">import</span> * <span class="keyword">as</span> example <span class="keyword">from</span> <span class="string">"./example.js"</span></span><br><span class="line"><span class="built_in">console</span>.log(example.a); <span class="comment">// 1</span></span><br><span class="line">sonsole.log(example.addA(<span class="number">1</span>); <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">console</span>.log(example.say2()); <span class="comment">// '没错我就是很帅'</span></span><br></pre></td></tr></table></figure>
<p>上面的导入整个模块就是把example.js中导出的所有元素全部加载到一个叫做example的对象中，而所导出的元素就会作为example的属性被访问。因为example对象是作为example.js中所导出成员的命名空间对象而被创建的，所以这种导入方式被称为命名空间导入（name space import)。</p>
<p>还有一点要注意的是，不管import语句把一个模块写了多少次，该模块只执行一次。意思就是，在首次执行导入模块后，实例化的模块就会被保存在内存中，只要使用import语句引用它就可以重复使用它：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 首次导入需要加载模块example.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; a &#125; <span class="keyword">from</span> <span class="string">"./example.js"</span></span><br><span class="line"><span class="comment">// 下面的两个import将无需加载example.js了</span></span><br><span class="line"><span class="keyword">import</span> &#123; addA &#125; <span class="keyword">from</span> <span class="string">"./example.js"</span></span><br><span class="line"><span class="keyword">import</span> &#123; say2 &#125; <span class="keyword">from</span> <span class="string">"./example.js"</span></span><br></pre></td></tr></table></figure>
<p>当从模块中导入一个元素时，它与const是一样无法定义另一个同名变量和导入一个同名元素，也无法在import语句前使用元素或者改变导出的元素的值：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//接上面的代码</span></span><br><span class="line"></span><br><span class="line">say2 = <span class="number">1</span> ;  <span class="comment">//会抛出一个错误</span></span><br></pre></td></tr></table></figure>
<p>这是由于ES6的import语句为导入的元素创建的是只读绑定的标识符，而不是原始绑定。因此元素只有在被导出的模块中才可以被修改，即使是将该模块的全部导入也无法修改其中的元素。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//   ./example.js</span></span><br><span class="line"><span class="comment">// 这是一个函数</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">setA</span>(<span class="params">newA</span>) </span>&#123;</span><br><span class="line">    a = newA;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//  ./say.js</span></span><br><span class="line"><span class="keyword">import</span> &#123; a, setA &#125; <span class="keyword">from</span> <span class="string">"./example"</span>;</span><br><span class="line"><span class="built_in">console</span>.log(a);  <span class="comment">// 1</span></span><br><span class="line">a = <span class="number">2</span>;   <span class="comment">//抛出错误</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 所以我们得这么做</span></span><br><span class="line">setA(<span class="number">2</span>); </span><br><span class="line"><span class="built_in">console</span>.log(a);  <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<p>调用setA(2)时会返回到example.js中去执行，将a设置为2。由于say.js导入的只是a的只读绑定的标识符而已，因此会自动进行更改。</p>
<h4 id="其他基本语法"><a href="#其他基本语法" class="headerlink" title="其他基本语法"></a>其他基本语法</h4><h5 id="1-语法限制"><a href="#1-语法限制" class="headerlink" title="1.语法限制"></a>1.语法限制</h5><p>export和import在语法上还有一个重要的限制，那就是他们必须在条件语句和函数之外使用，例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (ture) &#123;</span><br><span class="line">    <span class="keyword">export</span> <span class="keyword">var</span> a = <span class="number">1</span>;      <span class="comment">//语法错误</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">imp</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">import</span> a <span class="keyword">from</span> <span class="string">"./example.js"</span>; <span class="comment">//语法错误</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于模块语法存在的其中一个原因是让JavaScript引擎可以静态地确定哪些代码是可以导出的，因此export和import语句被设计成静态的，不能进行任何形式的动态导出或导入。</p>
<h5 id="2-重命名解决"><a href="#2-重命名解决" class="headerlink" title="2.重命名解决"></a>2.重命名解决</h5><p>有时在开发中，我们在导入一些元素后不想使用它们的原始名称了，我们就可以在导出过程或者导入过程中去改变导出元素的名称：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导出过程</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> &#123; add <span class="keyword">as</span> add1 &#125;;  <span class="comment">//在导入过程中必须使用add1作为名称 </span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 导入过程</span></span><br><span class="line"><span class="keyword">import</span> &#123;add <span class="keyword">as</span> add1 &#125; <span class="keyword">from</span> <span class="string">"./example"</span></span><br><span class="line"><span class="built_in">console</span>.log(add1(<span class="number">1</span>,<span class="number">1</span>));  <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="keyword">typeof</span> add); <span class="comment">//undefined</span></span><br></pre></td></tr></table></figure>
<h5 id="模块的默认值"><a href="#模块的默认值" class="headerlink" title="模块的默认值"></a>模块的默认值</h5><p>在CommonJS等其他的模块化规范中，从模块中导出或导入默认值是一个常见的用法，因此在ES6中也延用了这种用法并进行了优化。在ES6中我们可以使用default关键字来指定默认值，并且一个模块只能默认一个导出值：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ./example.js</span></span><br><span class="line"><span class="comment">// 第一种默认导出语法</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 第二种默认导出语法</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> add;</span><br><span class="line"><span class="comment">// 第三种默认导出语法</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">export</span> &#123; add <span class="keyword">as</span> <span class="keyword">default</span> &#125;;</span><br></pre></td></tr></table></figure>
<p>需要注意的是第三种语法，default关键字虽然不能作为元素的名称，但可以作为元素的属性名称，因此可以使用as语法将add函数的属性设置为default。</p>
<p>导入默认值的语法则是这样的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  第一种语法</span></span><br><span class="line"><span class="keyword">import</span> add <span class="keyword">from</span> <span class="string">"./example"</span>;</span><br><span class="line"><span class="comment">//  第二种语法</span></span><br><span class="line"><span class="keyword">import</span> &#123; <span class="keyword">default</span> <span class="keyword">as</span> add &#125; <span class="keyword">from</span> <span class="string">"./example"</span>;</span><br></pre></td></tr></table></figure>
<p>看到这里有些朋友可能会发现，我们的第一种语法中import关键字后面并没有加大括号，认为这是错误的。其实这是导入默认值的独特语法，在这的本地名称add用于表示模块导出的任何默认函数，这种语法是最纯净的，ES6标准创建团队的大佬们也希望这种语法能成为web主流的模块导入形式。</p>
<p>我们前面说的导入匿名函数也同样使用这种语法：<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ./example.js</span></span><br><span class="line"><span class="comment">//导出匿名函数</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a + b；</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// ./say.js</span></span><br><span class="line"><span class="keyword">import</span> add <span class="keyword">from</span> <span class="string">"./example"</span>;</span><br><span class="line"><span class="built_in">console</span>.log(add(<span class="number">1</span>,<span class="number">1</span>));  <span class="comment">// 2</span></span><br></pre></td></tr></table></figure></p>
<p>在这里本地名称add就是用于表示上面的匿名函数的。</p>
<h5 id="导出已导入的元素"><a href="#导出已导入的元素" class="headerlink" title="导出已导入的元素"></a>导出已导入的元素</h5><p>我们同样可以在本模块内导出我们在本模块内导入的元素，有以下几种语法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  第一种语法</span></span><br><span class="line"><span class="keyword">import</span> &#123; add &#125; <span class="keyword">from</span> ./example.js;</span><br><span class="line"><span class="keyword">export</span> &#123; add &#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//  第二种语法</span></span><br><span class="line"><span class="keyword">export</span> &#123; add &#125; <span class="keyword">from</span> ./example.js;</span><br><span class="line"></span><br><span class="line"><span class="comment">//换一个名称导出</span></span><br><span class="line"><span class="keyword">export</span> &#123; add <span class="keyword">as</span> add1 &#125; <span class="keyword">from</span> ./example.js; <span class="comment">//以add这个名称导入，再以add1的名称导出</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 导出整个模块</span></span><br><span class="line"><span class="keyword">export</span> *  <span class="keyword">from</span> ./example.js;</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/blog/tags/模块化/" rel="tag"># 模块化</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/05/06/变量提升和函数声明提升/" rel="next" title="变量提升和函数声明提升">
                <i class="fa fa-chevron-left"></i> 变量提升和函数声明提升
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/05/06/简述JavaScript模块化（一）/" rel="prev" title="简述JavaScript模块化历程（一）">
                简述JavaScript模块化历程（一） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="Srtian" />
            
              <p class="site-author-name" itemprop="name">Srtian</p>
              <p class="site-description motion-element" itemprop="description">JUST DO IT.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">59</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">37</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/srtian96" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="shenruotian@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#ES6模块特性"><span class="nav-number">1.</span> <span class="nav-text">ES6模块特性</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#基本用法-模块加载"><span class="nav-number">2.</span> <span class="nav-text">基本用法-模块加载</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#基本用法-导出"><span class="nav-number">3.</span> <span class="nav-text">基本用法-导出</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#基本语法-导入"><span class="nav-number">4.</span> <span class="nav-text">基本语法-导入</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#其他基本语法"><span class="nav-number">5.</span> <span class="nav-text">其他基本语法</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-语法限制"><span class="nav-number">5.1.</span> <span class="nav-text">1.语法限制</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-重命名解决"><span class="nav-number">5.2.</span> <span class="nav-text">2.重命名解决</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#模块的默认值"><span class="nav-number">5.3.</span> <span class="nav-text">模块的默认值</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#导出已导入的元素"><span class="nav-number">5.4.</span> <span class="nav-text">导出已导入的元素</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Srtian</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">102.8k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
